package RPC.rpc06;


import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Title 这里仅仅是实现了getUserByID方法的代理，如果有其他方法应怎么处理呢？
 * todo 协议层改进
 * @Author zhengqiang.tan
 * @Date 11/14/22 10:27 PM
 */
public class Server {
    private static boolean running = true;

    public static void main(String[] args) throws Exception {
        ServerSocket socket = new ServerSocket(8888);
        while (running) {
            Socket accept = socket.accept();
            process(accept);
            accept.close();
        }
        socket.close();
        System.out.println("启动服务器...");


    }

    /**
     * 对同一个接口下任意方法的支持
     *
     * @param s
     * @throws Exception
     */
    private static void process(Socket s) throws Exception {
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();
        ObjectInputStream ois = new ObjectInputStream(in);

        //服务器端解析这三个参数 并找到对应的方法
        String clazzName = ois.readUTF();
        String methodName = ois.readUTF();
        Class[] paramTypes = (Class[]) ois.readObject();
        Object[] args = (Object[]) ois.readObject();

        Class clazz = null;
        // 依据clazzName找到具体服务注册类，也可以使用Spring注入

        if (clazzName.contains("IUserService")) {
            clazz = UserServiceImpl.class;

        } else if (clazzName.contains("IProductService")) {
            clazz = ProductServiceImpl.class;
        }


        Method method = clazz.getMethod(methodName, paramTypes);
        Object o = method.invoke(clazz.newInstance(), args);

        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(o);
        oos.close();
        oos.flush();

    }
}
